package com.atguigu.guli.service.base.exception;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//对所有的Controller的异常进行处理
//@ControllerAdvice  处理异常后返回视图名称进行转发
@RestControllerAdvice//处理异常后将返回的数据转为json响应
@Slf4j
public class GlobalExceptionHandler {
    //编写异常处理器
    //捕获最大异常：Exception
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e){//形参类型必须和ExceptionHandler注解中的异常类型一样
        //将异常收集到异常日志文件中
        log.error("异常："+ ExceptionUtils.getStackTrace(e));
        //返回一个失败的异常
        return R.error();
    }
    //捕获sql异常：BadSqlGrammarException
    @ExceptionHandler(value = BadSqlGrammarException.class )
    public R exception(BadSqlGrammarException e){
        log.error("异常："+ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }
    //捕获json异常：HttpMessageNotWritableException
    @ExceptionHandler(value = HttpMessageNotWritableException.class )
    public R exception(HttpMessageNotWritableException e){
        log.error("异常："+ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }

    @ExceptionHandler(value = GuliException.class )
    public R exception(GuliException e){
        log.error("异常："+ExceptionUtils.getStackTrace(e));
        return R.setResult(e.getCodeEnum());
    }
}
